<script setup lang="ts">
import { onMounted, ref, getCurrentInstance, computed, watch, onUnmounted } from 'vue'
import Input from './common/Input.vue';
import { userStore } from '@/store/user';
import { getList } from '@/apis/currency';
import { CoinItem } from "@/interfaces/currency.js";
import { useCoinStore } from '@/store/coin';
import { formatNumberWithThousands } from '@/utils/utils';
const instance = getCurrentInstance()
const currencyId = ref<string>()
let currencySocket: any
const emit = defineEmits(['changeCoin'])
const activeCode = ref<string>('USDT')
const activeList = ref([
    { title: '自选', code: 'optional', left: '8px' },
    { title: 'USDT', code: 'USDT', left: '51px' },
])
const obj = computed(() => {
    let info = {} as any
    useCoinStore().coinPriceList.forEach(item => {
        info[item.coinName] = item
    })
    return info
}) as any

const connectCurrency = () => {
    if (currencyId.value) {
        currencySocket.unsubscribe(currencyId.value, '/topic/market')
    }
    currencyId.value = Date.now().toString(36) + Math.floor(Math.random() * 1000).toString(36)
    currencySocket.subscribe(currencyId.value, `/topic/market`, (data: CoinItem) => {
        let item = coinList.value?.find(item => item.currencyPair === data.currencyPair)
        if (item) {
            Object.assign(item, data)
        }
        item = data
    })
}

const getSrc = (name: string): string => {
    const logoList = useCoinStore().logoList as Record<string, string> || []
    return 'https://file.uhx.io/' + logoList[name] || ''
}
const coinList = ref<CoinItem[]>([])
const myLove = computed(() => {
    return coinList.value.filter(item => userStore().loveList.includes(item.currencyPair.split('-')[0]))
})
const getListFn = async () => {
    const list = await getList()
    coinList.value = list
    changeCoin(coinList.value.find(item => item.currencyPair === useCoinStore().coinInfo.name + '-USDT') as CoinItem)
}

const changeCoin = (item: CoinItem) => {
    const name = item.currencyPair.split('-')[0]
    useCoinStore().setCoinName(name)
    useCoinStore().setCoinPrice(item.amount + '')
    emit('changeCoin')
}
const addLove = (item: any) => {
    const coinName = item.currencyPair.split('-')[0]
    if (userStore().loveList.includes(coinName)) {
        userStore().remvoeLoveItem(coinName)
    } else {
        userStore().addLoveItem(coinName)
    }
}
watch(() => useCoinStore().spotKLine, (val) => {
    if (val) {
        for (let i = 0; i < coinList.value.length; i++) {
            const item = coinList.value[i]
            const currencyPair = coinList.value[i].currencyPair
            if (val[currencyPair]) {
                Object.assign(item, val[currencyPair])
            }
        }
    }
}, {
    deep: true
})
// watch(() => userStore().currencySocket, (val) => {
//     if (val) {
//         if (instance) {
//             currencySocket = instance.appContext.config.globalProperties.$currencySocket
//             if (currencySocket.connected) {
//                 connectCurrency()
//             }
//         }
//     }
// }, { immediate: true })
onMounted(() => {
    getListFn()
})
onUnmounted(() => {
    // if (currencySocket) {
    //     currencySocket.unsubscribe(currencyId.value, '/topic/market')
    // }
})
</script>

<template>
    <div class="h-full box-border">
        <div class="px-[16px]">
            <div
                class=" mx-[-16px]  px-[16px] text-[14px] pt-[10px] flex flex-col justify-between  border-0  border-b-[1px] border-[#ededed] dark:border-[#333b47] border-solid">
                <Input class="!h-[32px] placeholder:text-[14px] relative z-[3] rounded-[6px]" placeholder="查询" />
                <div class="h-[30px] mt-[10px]  flex items-center text-[14px] font-[500] relative">
                    <div v-for="item, i in activeList" :key="i" @click="activeCode = item.code"
                        :class="[item.code === activeCode ? 'text-black dark:text-[#eaecef]' : 'text-text dark:text-[#929AA5]']"
                        class=" mr-[10px]  cursor-pointer h-[30px] leading-[30px] hover:text-black dark:hover:text-[#eaecef]">
                        {{ item.title }}
                    </div>
                    <span class=" absolute bottom-0 w-[16px] h-[3px] bg-primary-300"
                        :style="{ left: activeList.find(item => item.code === activeCode)?.left }"></span>
                </div>
            </div>
        </div>
        <div class=" box-border pt-[10px] h-[calc(100%-92px)] ">
            <div v-show="activeCode === 'USDT'">
                <div
                    class="h-[24px] mb-[4px] px-[16px] box-border flex items-center justify-between w-full text-[12px] text-text dark:text-[#707a8a]">
                    <div class="w-5/12">交易对</div>
                    <div class="w-4/12 text-right">最新价格</div>
                    <div class="w-3/12 text-right">24h涨跌</div>
                </div>
                <div class="h-[calc(100%-28px)] scroll" v-if="coinList.length">
                    <div @click="changeCoin(item)" v-for="(item, i) in coinList" :key="i"
                        class="h-[24px] px-[16px] box-border flex items-center justify-between w-full text-[12px] text-text cursor-pointer sm:hover:bg-[#f5f5f5] sm:dark:hover:bg-[#29313d]">
                        <div class="w-5/12 whitespace-nowrap  text-black dark:text-[#eaecef] flex items-center">
                            <div @click.stop="addLove(item)"
                                :class="[userStore().loveList.includes(item.currencyPair.split('-')[0]) ? 'icon-shoucang1 text-[#f0b90b]' : 'icon-shoucang text-[#bfbfbf] dark:text-[#4f5867]']"
                                class="iconfont icon-shoucang"></div>
                            <img :src="getSrc(item.currencyPair.split('-')[0])" class="w-[16px] ml-[4px] " />
                            <div class="ml-[4px]">{{
                                item.currencyPair
                            }}</div>
                        </div>
                        <div class="w-4/12 text-right text-black dark:text-[#eaecef]">{{
                            obj[(item.currencyPair.split('-')[0])]?.unitDecimals ?
                                formatNumberWithThousands(item.amount.toFixed(obj[(item.currencyPair.split('-')[0])].unitDecimals))
                                : formatNumberWithThousands(item.amount) }}
                        </div>
                        <div class="w-3/12 text-right" :class="[item.percent * 100 > 0 ? 'text-rise' : 'text-fall']">{{
                            item.percent
                                > 0 ? '+' : '' }}{{ Number(item.percent * 100).toFixed(2) }}%</div>
                    </div>
                </div>
            </div>
            <div v-show="activeCode === 'optional'" class="h-full">
                <template v-if="myLove.length">
                    <div
                        class="h-[24px] mb-[4px] px-[16px] box-border flex items-center justify-between w-full text-[12px] text-text dark:text-[#707a8a]">
                        <div class="w-5/12">交易对</div>
                        <div class="w-1/3 text-right">最新价格</div>
                        <div class="w-3/12 text-right">24h涨跌</div>
                    </div>
                    <div class="h-[calc(100%-28px)] overflow-scroll">
                        <div @click="changeCoin(item)" v-for="(item, i) in myLove" :key="i"
                            class="h-[24px] px-[16px] box-border flex items-center justify-between w-full text-[12px] text-text cursor-pointer sm:hover:bg-[#f5f5f5] sm:dark:hover:bg-[#29313d]">
                            <div class="w-5/12 whitespace-nowrap  text-black dark:text-[#eaecef] flex items-center">
                                <div @click.stop="addLove(item)"
                                    :class="[userStore().loveList.includes(item.currencyPair.split('-')[0]) ? 'icon-shoucang1 text-[#f0b90b]' : 'icon-shoucang text-[#bfbfbf] dark:text-[#4f5867]']"
                                    class="iconfont icon-shoucang"></div>
                                <img :src="getSrc(item.currencyPair.split('-')[0])" class="w-[16px] ml-[4px]" />
                                <div class="ml-[4px]">{{
                                    item.currencyPair
                                }}</div>
                            </div>
                            <div class="w-1/3 text-right text-black dark:text-[#eaecef]">{{
                                obj[(item.currencyPair.split('-')[0])]?.unitDecimals ?
                                    item.amount.toFixed(obj[(item.currencyPair.split('-')[0])].unitDecimals) : item.amount
                            }}</div>
                            <div class="w-1/4 text-right" :class="[item.percent * 100 > 0 ? 'text-rise' : 'text-fall']">
                                {{
                                    item.percent
                                        > 0 ? '+' : '' }}{{ Number(item.percent * 100).toFixed(2) }}%</div>
                        </div>
                    </div>
                </template>
                <template v-else>
                    <div class="flex items-center justify-center h-full flex-col">
                        <span class="iconfont icon-no-data text-[#9c9c9c] text-[40px]"></span>
                        <div class="mt-[5px] text-[#9c9c9c] text-[14px]">暂无数据</div>
                    </div>
                </template>
            </div>
        </div>
    </div>
</template>

<style scoped></style>